<template>
  <n-card :bordered="false" class="proCard">
    <BasicTable
      title="账变记录"
      titleTooltip="显示所有账变记录信息"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :scroll-x="900"
      @update:checked-row-keys="onCheckedRow"
    />
  </n-card>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { BasicTable } from '@/components/Table';
  import { getChangeRecords } from '@/api/billing';
  import { columns } from './columns';

  const actionRef = ref();

  const params = reactive({
    pageSize: 10,
    unique_str: 'customer_E590CEED9FE274220DF432712AA3F6DE',
  });

  const loadDataTable = async (res: any) => {
    const requestParams = {
      ...params,
      page: res.page || 1,
      pageSize: res.pageSize || 10,
    };
    
    try {
      const response = await getChangeRecords(requestParams);
      
      console.log('账变记录API响应数据:', response); // 调试日志
      
      // 检查响应状态
      if (response && typeof response === 'object' && 'code' in response) {
        const { code, message, data } = response as any;
        
        // 如果返回错误码，显示错误提示
        if (code !== 200 && code !== 0) {
          // @ts-ignore
          window.$message?.error(message || '获取账变记录失败');
          return {
            list: [],
            page: 1,
            pageSize: 10,
            pageCount: 0,
            itemCount: 0,
          };
        }
        
        // 成功时处理数据 - data 字段包含分页信息和实际数据
        return {
          list: data?.data || [],
          page: data?.current_page || 1,
          pageSize: data?.per_page || 10,
          pageCount: data?.last_page || 1,
          itemCount: data?.total || 0,
        };
      }
      
      // 异常情况：响应格式不正确
      console.warn('响应格式异常:', response);
      // @ts-ignore
      window.$message?.error('响应数据格式异常');
      return {
        list: [],
        page: 1,
        pageSize: 10,
        pageCount: 0,
        itemCount: 0,
      };
    } catch (error) {
      console.error('获取账变记录失败:', error);
      
      // 显示错误提示
      // @ts-ignore
      window.$message?.error('获取账变记录失败，请稍后重试');
      
      return {
        list: [],
        page: 1,
        pageSize: 10,
        pageCount: 0,
        itemCount: 0,
      };
    }
  };

  function onCheckedRow(rowKeys: any) {
    console.log('选中的行:', rowKeys);
  }
</script>

<style lang="less" scoped></style>